﻿using BaseUtils;
using BaseUtils.Logger;
using Service.src;
using Service.src.NW.UI;
using System;
using System.Diagnostics;
using System.Management;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Service
{
    internal static class Program
    {
        static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45FD-A8CF-72F04E6BDE8F}");
        //private static bool MultiOpenApp  = false;
        /// <summary>
        /// 应用程序的主入口点 。 
        /// </summary>
        [STAThread]
        static void Main()
        {  
  
            //sdfsf();
            InitAppConfig();
            Process currentProcess = Process.GetCurrentProcess();
            // 获取当前进程名称
            string processName = currentProcess.ProcessName;
            Process[] ps = Process.GetProcessesByName(processName);
            bool MultiOpenApp = (bool)(BaseService.AppConfig?.field?.MultiOpenApp);
            // 检查是否有其他相同的进程在运行
            if (!mutex.WaitOne(TimeSpan.Zero, true) && !MultiOpenApp)
            {
                MessageBox.Show("程序已经在运行。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (!MultiOpenApp)
            {
                mutex.ReleaseMutex();
            }
            AuthorizationVerification();
            ApplicationException();
            Task.Run(() =>
            {
                // ExecuteBat("\\nginx-1.24.0\\stop.bat");
                Thread.Sleep(1000);
                if (BaseService.AppConfig.field.EnableWindowFile)
                {
                    ExecuteBat("\\nginx-1.24.0\\start.bat");
                }
            });

            // 先初始化UI线程（关键步骤）
            // UIThreadManager.Init();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new NWStudioHomeForm());
        }

        public static bool ExecuteBat(string bat, string workingDirectory = null, bool visible = false)
        {
            string batFilePath = AppDomain.CurrentDomain.BaseDirectory + bat;
            // 检查文件是否存在
            if (!System.IO.File.Exists(batFilePath))
            {
                MessageBox.Show($"批处理文件不存在：{batFilePath}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            try
            {
                // 创建进程启动信息
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "cmd.exe"; // 使用cmd.exe执行批处理
                startInfo.Arguments = $"/c \"{batFilePath}\""; // /c 参数表示执行后关闭窗口

                // 设置工作目录（批处理中相对路径的基准）
                if (!string.IsNullOrEmpty(workingDirectory))
                {
                    startInfo.WorkingDirectory = workingDirectory;
                }
                else
                {
                    // 默认使用批处理文件所在目录
                    startInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(batFilePath);
                }

                // 设置是否显示命令窗口
                startInfo.WindowStyle = visible ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden;
                startInfo.CreateNoWindow = !visible;

                // 启动进程
                using (Process process = Process.Start(startInfo))
                {
                    // 等待批处理执行完成
                    process.WaitForExit();

                    // 返回执行结果（0表示成功，非0表示出错）
                    return process.ExitCode == 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"执行批处理出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private static void sdfsf()
        {// 输入点
         // 定义已知的两个点
            Point point1 = new Point(0, 1);
            Point point2 = new Point(1, 0);

            // 计算圆心坐标
            Point[] centers = CalculateCircleCenters(point1, point2);

            // 输出结果

            foreach (var center in centers)
            {
                Console.WriteLine("({0}, {1})", center.X, center.Y);
            }

            dsfsfsdf();
            //double x = 0, y = 1;  // 原坐标
            //double angle = -90;   // 旋转角度（度）

            //// 转换为弧度
            //double radians = angle * Math.PI / 180;
            //double cos = Math.Cos(radians);
            //double sin = Math.Sin(radians);

            //// 旋转公式
            //double newX = x * cos - y * sin;
            //double newY = x * sin + y * cos;

            Console.WriteLine("已知点1: ({0}, {1})", point1.X, point1.Y);
            Console.WriteLine("已知点2: ({0}, {1})", point2.X, point2.Y);
            Console.WriteLine("可能的圆心坐标:");
        }

        private static void dsfsfsdf()
        {
            double x = 0, y = 1;          // 原坐标
            double cx = 0, cy = 0;        // 旋转中心（示例：(2, 3)）
            double angle = -90;           // 旋转角度（度）

            // 转换为弧度
            double radians = angle * Math.PI / 180;
            double cos = Math.Cos(radians);
            double sin = Math.Sin(radians);

            // 平移到旋转中心
            double tx = x - cx;
            double ty = y - cy;

            // 绕原点旋转
            double rx = tx * cos - ty * sin;
            double ry = tx * sin + ty * cos;

            // 平移回原坐标系
            double newX = rx + cx;
            double newY = ry + cy;

            Console.WriteLine($"原坐标: ({x}, {y})");
            Console.WriteLine($"旋转中心: ({cx}, {cy})");
            Console.WriteLine($"旋转{-angle}度后的坐标: ({newX:F6}, {newY:F6})");
        }

        static Point[] CalculateCircleCenters(Point p1, Point p2)
        {
            // 计算两点连线的中点
            double midX = (p1.X + p2.X) / 2;
            double midY = (p1.Y + p2.Y) / 2;

            // 计算两点之间的距离
            double dx = p2.X - p1.X;
            double dy = p2.Y - p1.Y;
            double distance = Math.Sqrt(dx * dx + dy * dy);

            // 计算可能的圆心坐标
            double radius = distance / Math.Sqrt(2);

            // 计算两个可能的圆心
            Point center1 = new Point(
                midX + (p1.Y - midY),
                midY - (p1.X - midX)
            );

            Point center2 = new Point(
                midX - (p1.Y - midY),
                midY + (p1.X - midX)
            );

            return new Point[] { center1, center2 };
        }

        struct Point
        {
            public double X { get; set; }
            public double Y { get; set; }

            public Point(double x, double y)
            {
                X = x;
                Y = y;
            }
        }
        private static void AuthorizationVerification()
        {
            // 获取硬盘序列号
            string hardDiskSerialNumber = GetHardDiskSerialNumber();
            Console.WriteLine("硬盘序列号: " + hardDiskSerialNumber);

            // 获取BIOS序列号
            string biosSerialNumber = GetBIOSSerialNumber();
            Console.WriteLine("BIOS序列号: " + biosSerialNumber);
        }

        static string GetHardDiskSerialNumber()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_DiskDrive");
            foreach (ManagementObject mo in searcher.Get())
            {
                string serialNumber = mo["SerialNumber"].ToString();
                if (!string.IsNullOrEmpty(serialNumber))
                {
                    return serialNumber;
                }
            }
            return null;
        }

        static string GetBIOSSerialNumber()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BIOS");
            foreach (ManagementObject mo in searcher.Get())
            {
                string serialNumber = mo["SerialNumber"].ToString();
                if (!string.IsNullOrEmpty(serialNumber))
                {
                    return serialNumber;
                }
            }
            return null;
        }

        /// <summary>
        /// 注册事件处理程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            // 在这里处理异常，如记录日志等
            LoggerService.Error($"发生了未处理的异常：{ex.Message}", ex);
        }

        /// <summary>
        /// 定义事件处理方法
        /// "http://localhost:5173/#/chart/preview/46
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs ex)
        {
            LoggerService.Error($"发生了严重的未处理异常：{ex.Exception.Message}", ex.Exception);
        }

        /// <summary>
        /// 初始化 APP 
        /// </summary>
        static void InitAppConfig()
        {
            //ParseSql testreult = new ParseSql(ParseSql.test)
            //    .GetOperation().GetTableName().GetColumn().GetWhere().GetOrderBy().GetGroupBy().GetLimit().GetOffset();
            new BaseService("AppConfig.xml");
            new AppService();
        }

        /// <summary>
        /// 程序异常处理
        /// </summary>
        static void ApplicationException()
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

        }
    }
}
